package com.ocgs.base.core.web.interceptor;

import com.ocgs.base.core.exception.BaseException;
import com.ocgs.base.core.exception.WebException;
import com.ocgs.base.core.web.action.IBaseAction;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class GlobalLogInterceptor extends AbstractInterceptor implements HttpSessionListener {

    private static final long serialVersionUID = 1L;
    private static final Log log = LogFactory.getLog(GlobalLogInterceptor.class);

    public String intercept(ActionInvocation invocation) throws Exception {
        String result = null;
        log.info("-----------into the intercept---------------");
        if (!(invocation.getAction() instanceof IBaseAction)) {
            throw new WebException("Action must implements IBaseAction!");
        }
        IBaseAction action = (IBaseAction)invocation.getAction();
        try {
            log.info("****************Go into the Action:" + invocation.getAction() + "************");
            result = invocation.invoke();
            log.info("****************Out of the Action:" + action.getClass().getName() + "************");
        } catch (Exception e) {
            log.error("This is uncaughtable exception handled by GlobalExceptionHandler!", e);
            log.info("****************Out of the Action:" + action.getClass().getName() + " with error message " + e.getMessage() + "************");
            throw new BaseException(e.getMessage());
        }
        return result;
    }

    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
    }

    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
    }
}
